package com.fsd.admin.controller;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.fsd.core.bean.shiro.UsernamePasswordCaptchaToken;
import com.fsd.admin.entity.A_LoginInfo;
import com.fsd.admin.model.A_Company;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.service.A_CompanyService;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.service.Sys_PopedomAllocateService;
import com.fsd.admin.service.Sys_SystemLogService;
import com.fsd.admin.shiro.helper.ShiroSecurityHelper;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
@RequestMapping("/admin")
public class mainController extends BaseController{
	
	private static final Logger log = Logger.getLogger(mainController.class);
	
	@Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService a_EmployeeService;
	
	@Resource(name = "Sys_PopedomAllocateServiceImpl")
	private Sys_PopedomAllocateService sys_PopedomAllocateService;
	
	@Resource(name = "Sys_SystemLogServiceImpl")
    private Sys_SystemLogService sysLogService;
	
	@Resource(name = "A_CompanyServiceImpl")
	private A_CompanyService objectService;
	
    @Autowired
    private SessionDAO sessionDAO;
    
    private Producer captchaProducer = null;
	 
	@Autowired  
	public void setCaptchaProducer(Producer captchaProducer) {
		this.captchaProducer = captchaProducer;
	}
    /**
     * 登陆
     * @param Loginname
     * @param Password
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login.do")
	public @ResponseBody Map<String, Object> login(String Loginname, String Password, String Captcha, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	
    	//防止同一客户端多次登录
    	Subject currentUser = SecurityUtils.getSubject();
//		if (currentUser.isAuthenticated()) {
//			log.info("同一客户端防止无意义多次登录......");
//			return ParametersUtil.sendList();
//		}
		
		//防止同一用户名多处登录
    	Session RepeatSession = ShiroSecurityHelper.getSessionByUsername(sessionDAO, Loginname);
    	if(RepeatSession != null){
    		log.info(Loginname + ":该用户名已再别处登录，现以踢出......");
    		ShiroSecurityHelper.kickOutUser(RepeatSession);
    	}
    	String ldapPassword = Password;
    	if(!"admin".equals(Loginname)){
			ldapPassword = "cxcy123456";
		}
    	//验证登录
		UsernamePasswordCaptchaToken token = new UsernamePasswordCaptchaToken(Loginname, ldapPassword, Password, Captcha);
		token.setRememberMe(false);
		try {
			currentUser.login(token);
		} catch (ExcessiveAttemptsException e) {
			//记录登陆日志
			A_Employee user = a_EmployeeService.getObjectByUsername(Loginname);
        	this.sysLogService.saveObject(Config.LOGTYPEDLSB, user.getId() + user.getRealname()+ ",用户名'"+Loginname+"'密码错误次数过多，限制登录10分钟！", user, mainController.class);
			throw e;
		}
		
		
		//验证登录通过，将用户信息放入session
		if(null != currentUser){
			Session session = currentUser.getSession();
	        if(null != session){
	        	log.info("验证登录通过，将用户信息放入session......");
	        	A_Employee user = a_EmployeeService.getObjectByUsername(Loginname);

	        	if(user.getLoginname().indexOf("admin") == 0){
					user.setIsadmin(true);
				}

	        	A_LoginInfo loginInfo = new A_LoginInfo();
	    		loginInfo.setEmployee(user);
	    		A_Company company = objectService.getObjectById(user.getCompanyid());
	    		loginInfo.setCompany(company);
	    		Map<String, List<String>> popedomMap = sys_PopedomAllocateService.getUserPopedomMap(user);
	    		loginInfo.setPopedomMap(popedomMap);
	        	ShiroSecurityHelper.setUserToSession(session, loginInfo);
	        	
	        	//记录登陆日志
	        	this.sysLogService.saveObject(Config.LOGTYPEDL, user.getId() + "-" +user.getRealname()+",通过IP："+request.getRemoteAddr()+"登录！", user, mainController.class);
	        }
		}
		
		return ParametersUtil.sendList();
	}
    
    /**
     * 切换站点
     * @param id
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/changeSiteInfo.do")
	public @ResponseBody Map<String, Object> changeSiteInfo(String id, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	
    	A_Employee adminEmp = (A_Employee) a_EmployeeService.getObjectByCompany(id);
    	
    	Subject currentUser = SecurityUtils.getSubject();
		
		//防止同一用户名多处登录
    	Session RepeatSession = ShiroSecurityHelper.getSessionByUsername(sessionDAO, adminEmp.getLoginname());
    	if(RepeatSession != null){
    		log.info(adminEmp.getLoginname() + ":该用户名已再别处登录，现以踢出......");
    		ShiroSecurityHelper.kickOutUser(RepeatSession);
    	}
    	
		//验证登录通过，将用户信息放入session
		Session session = currentUser.getSession();
        if(null != session){
        	A_Employee user = a_EmployeeService.getObjectByUsername(adminEmp.getLoginname());
			if(user.getLoginname().indexOf("admin") == 0){
				user.setIsadmin(true);
			}
        	A_LoginInfo loginInfo = new A_LoginInfo();
    		loginInfo.setEmployee(user);
    		A_Company company = objectService.getObjectById(user.getCompanyid());
    		loginInfo.setCompany(company);
    		Map<String, List<String>> popedomMap = sys_PopedomAllocateService.getUserPopedomMap(user);
    		loginInfo.setPopedomMap(popedomMap);
        	ShiroSecurityHelper.setUserToSession(session, loginInfo);
        	
        }
		return ParametersUtil.sendList();
	}
    
    /**
     * 退出登陆
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/logout.do")
    public @ResponseBody Object logout(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		log.info("退出了。。。。。");
    		ShiroSecurityHelper.kickOutUser(subject.getSession());
    		subject.logout();
    	}
    	return ParametersUtil.sendList();
    }
    
    /**
     * 生成验证码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/captcha-image")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        // store the text in the session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}